#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("服务端");

    tcpServer = new QTcpServer(this);

    this->connect(tcpServer, &QTcpServer::newConnection, this, &Widget::processConnect);

    bool ret = tcpServer->listen(QHostAddress::Any, 9090);
    if(!ret)
    {
        QMessageBox::critical(this, "服务器启动失败", tcpServer->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnect()
{
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    QString addr = clientSocket->peerAddress().toString();
    QString port = QString::number(clientSocket->peerPort());
    QString log = "["+addr+":"+port+"]"+" 上线!";
    ui->listWidget->addItem(log);

    this->connect(clientSocket, &QTcpSocket::readyRead, this, [=](){
        QString request = clientSocket->readAll();

        QString response = process(request);

        clientSocket->write(response.toUtf8());

        QString log = "["+addr+":"+port+"]"+" 请求: "+request+" 响应: "+response;
        ui->listWidget->addItem(log);
    });

    this->connect(clientSocket, &QTcpSocket::disconnected, this, [=](){
        QString addr = clientSocket->peerAddress().toString();
        QString port = QString::number(clientSocket->peerPort());
        QString log = "["+addr+":"+port+"]"+" 下线!";
        ui->listWidget->addItem(log);

        clientSocket->deleteLater();
    });

}

QString Widget::process(QString request)
{
    return request;
}

